package arithmetic.functionTest.myStream;

import java.util.Iterator;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * 终止节点的Ops
 * 类似工具类
 * Created on 2020-04-26
 */
final class MyForEachOps {

    private MyForEachOps() { }


    public static <T> MyTerminalOp<T, Void> makeRef(Consumer<? super T> action,
            boolean ordered) {
        Objects.requireNonNull(action);
        return new ForEachOp.OfRef<>(action, ordered);
    }

    static abstract class ForEachOp<T>
            implements MyTerminalOp<T, Void>, MyTerminalSink<T, Void> {
        private final boolean ordered;

        protected ForEachOp(boolean ordered) {
            this.ordered = ordered;
        }


        /**
         * foreach 就没有输出 所以输出类型为Void
         * @param helper
         * @param iterator
         * @param <S>
         * @return
         */
        // final <P_IN, S extends MySink<E_OUT>> S wrapAndCopyInto(S sink, Iterator<P_IN> iterator) {
        @Override
        public <S> Void evaluateSequential(MyPipelinHelper<T> helper,
                Iterator<S> iterator) {
            return helper.wrapAndCopyInto(this, iterator).get();
        }

        @Override
        public Void get() {
            return null;
        }


        static final class OfRef<T> extends MyForEachOps.ForEachOp<T> {

            final Consumer<? super T> consumer;

            OfRef(Consumer<? super T> consumer, boolean ordered) {
                super(ordered);
                this.consumer = consumer;
            }

            @Override
            public void accept(T t) {
                consumer.accept(t);
            }

        }
    }
}
